package com.example.mcu_up.util;

 
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
 
/**
 * @author 码农小江
 * H20121012.java
 * 2012-10-12下午11:40:21
 */
public class MCU_Reader {
    /**
     * 功能：Java读取txt文件的内容
     * 步骤：1：先获得文件句柄
     * 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
     * 3：读取到输入流后，需要读取生成字节流
     * 4：一行一行的输出。readline()。
     * 备注：需要考虑的是异常情况
     * @param filePath
     */
    public static String[] readTxtFile(String filePath){
        StringBuffer buffer=new StringBuffer();
        try {
                String encoding="GBK";
                File file=new File(filePath);
                if(file.isFile() && file.exists()){ //判断文件是否存在
                    InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file),encoding);//考虑到编码格式
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt=null;
                    while((lineTxt = bufferedReader.readLine()) != null){
                    	if(lineTxt.startsWith(":"))
                    		lineTxt=lineTxt.substring(1);
                        buffer.append(lineTxt+",");
                    }
                    read.close();
                 
        }else{
            System.out.println("找不到指定的文件");
        }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        
        return    buffer.toString().split(",");
     
    }
     
    public static byte[][] getSendBytes(String path){
    	String[] s=readTxtFile(path);
        byte[][] bb=new byte[s.length-1][s[1].length()];
        byte[][] out=new byte[s.length-1][s[1].length()];
          for(int j=1;j<s.length;j++)
        	   bb[j-1]=hex2Byte(s[j]);
           for(int i=0;i<bb.length;i++)
                 out[i]=subByte(bb[i],5,1);
    	return out;
    }
    
    
    
    public  static String readFirst(String filePath){
    	return readTxtFile(filePath)[0];
    }
    
    
    
    
    public static byte[] subByte(byte[] b,int start,int end){
    	
    	   byte[] bbs=new byte[b.length-start-end];
    	   	
    	   	for(int i=start;i<b.length-end;i++)
    	   	     bbs[i-start]=b[i];
    	       
    	return bbs;
   
    }
    
    
    public static byte[] subSend(byte[] b,int start,int end){
    	byte[] send=new byte[end -start];
    	int j=0;
    	for(int i=start;i<end;i++){
    		 send[j++]=b[i];
    	}
    	
    	return send;
    }
    
    
    
    
    
    
    
    
    
    public static void main(String argv[]){
        String filePath = "D:\\o2fw-010120150505.cyacd";
       // String sss="00002300800010002091110000752600007526000008B5024B83F3088801F06EFA00100020F7B572B680220021D2007A4804F0ACFC802200217848D20004F0A6FC0023191C764C18591C34C2B20192071CFF2297434A00A4180022019ED5B2AE4209D05500665D6519B446BC446D78664635700132F1E7C0B2043309181C2BE1D1684BE022AA";
       // System.out.println(readTxtFile(filePath)[1]);
      
    	   
      String  sss=readTxtFile(filePath)[1];
    /*  
      byte[] b=hex2Byte(sss);
   
    	  System.out.print(byteToString(b));
      */
      
     /*   for(int i=0;i<sss.length()-2;i=i+2){
		int beginIndex=i;
		int endIndex=i+2;
		String a = sss.substring( beginIndex,  endIndex);
		System.out.print("(byte)0x"+a+" ,");
	}*/
        
        
       
       byte[][] b=getSendBytes(filePath);
       
      /* for(byte[] bb:b){
    	   System.out.println(byteToString(bb));
       }*/
       
       
       
       System.out.println(byteToString(b[0]));
       System.out.print(byteToString(subSend(b[0],0,53))+",");
       System.out.print(byteToString(subSend(b[0],53,106))+",");
       System.out.print(byteToString(subSend(b[0],106,128)));
     /* 
      String ss=s[14];
     
      byte[] hexStringToBytes = hex2Byte(ss);
      
      
      byte[][] bb=new byte[6][49];
      
      for(int j=0;j<6;j++)
    	  for(int i=49*j, n=0;i<49*(j+1);i++,n++)
    		  bb[j][n]=hexStringToBytes[i];
      
      
      */
   
 
      
  //  System.out.println(byteToString(hexStringToBytes));
   
    

   // for(int i=0;i<6;i++)
   // System.out.print(byteToString(bb[i]));
    
    
   /* byte[][][]  blines=toAll(filePath);
     for(int i=0;i<blines.length;i++)
    	   for(int j=0;j<blines[i].length;j++){
    		   if(j==5)
    			   System.out.println(byteToString(blines[i][j]));
    		   else
    			   System.out.print(byteToString(blines[i][j]));
    		   
    	   }
        }*/
      
      
      
  
    }
    
    
	public static String byteToString(byte[] b){
		StringBuffer buffer=new StringBuffer(b.length);
		for(int i=0;i<b.length;i++){
			 String strHex = Integer.toHexString(b[i]).toUpperCase();
			 if(strHex.length()>3){
				 buffer.append(strHex.substring(6)+" ");
			 }else if(strHex.length()<2){
				 buffer.append("0" + strHex+" ");
			 }else{		 
				 buffer.append(strHex+" ");
			 }
		}
		return buffer.toString(); 
	}
    
	/**
	 * 16进制的字符串表示转成字节数组
	 *
	 * @param hexString
	 *			16进制格式的字符串
	 * @return 转换后的字节数组
	 **/
	public static byte[] hexStr2ByteArray(String hexString) {
	
 
		hexString = hexString.toLowerCase();
		final byte[] byteArray = new byte[hexString.length() / 2];
		int k = 0;
		for (int i = 0; i < byteArray.length; i++) {
						//因为是16进制，最多只会占用4位，转换成字节需要两个16进制的字符，高位在先
						//将hex 转换成byte   "&" 操作为了防止负数的自动扩展
						// hex转换成byte 其实只占用了4位，然后把高位进行右移四位
						// 然后“|”操作  低四位 就能得到 两个 16进制数转换成一个byte.
						//
			byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
			byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
			byteArray[i] = (byte) (high << 4 | low);
			k += 2;
		}
		return byteArray;
	}

   /**
    * 16进制字符串转换成byte数组
    * @param 16进制字符串
    * @return 转换后的byte数组
    */
  	public static byte[] hex2Byte(String hex) {
		String digital = "0123456789ABCDEF";
		char[] hex2char = hex.toCharArray();
		byte[] bytes = new byte[hex.length() / 2];
		int temp;
		for (int i = 0; i < bytes.length; i++) {
		// 其实和上面的函数是一样的 multiple 16 就是右移4位 这样就成了高4位了
		// 然后和低四位相加， 相当于 位操作"|" 
		//相加后的数字 进行 位 "&" 操作 防止负数的自动扩展. {0xff byte最大表示数}
			temp = digital.indexOf(hex2char[2 * i]) * 16;
			temp += digital.indexOf(hex2char[2 * i + 1]);
			bytes[i] = (byte) (temp & 0xff);
		}
		return bytes;
	}
  
  	
  	
  	
  	
  
  	
  	
  	
  	
  	
  	
  	
  	public static byte[][] toSixByte(String hex){
  	    byte[][] bb=new byte[6][134];
        byte[] bytes=hex2Byte(hex);
        for(int j=0;j<6;j++)
      	  for(int i=49*j, n=0;i<49*(j+1);i++,n++)
      		  bb[j][n]=bytes[i];
        return bb;
  	}
  	
  	
  	public static byte[][][] toAll(String path){
  		
  		String[] s=readTxtFile(path);
  		byte[][][] blines=new byte[s.length-1][6][49];
  		for(int i=1;i<s.length;i++)
  				blines[i-1]=toSixByte(s[i]);
  		return blines;
  	 	
  	}
}